<template>
  <div class="dialog-form">
    <el-form :model="form" :rules="rules" ref="userRef" label-width="100px">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="所属公司" prop="coId">
            <el-tree-select
              v-model="form.coId"
              :data="companyList"
              :render-after-expand="true"
              :props="treeProps"
              node-key="id"
              :default-expanded-keys="expandedKeys"
              check-strictly
              @change="handleCompanyChange"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="所属部门" prop="deptId">
            <el-select v-model="form.deptId" placeholder="请选择" :disabled="!form.coId">
              <el-option
                v-for="dict in departList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
                :disabled="dict.state == 2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="登录用户名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入登录用户名" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!form.userId">
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :value="dict.value"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户角色" prop="roleIds">
            <el-select v-model="form.roleIds" multiple collapse-tags placeholder="请选择">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据权限" prop="dataPermissions">
            <el-radio-group v-model="form.dataPermissions">
              <el-radio :value="1">全部数据权限</el-radio>
              <el-radio :value="2">自定义数据权限</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.dataPermissions == 2">
          <el-form-item label="数据权限" prop="companyId">
            <el-tree-select
              v-model="form.companyId"
              :data="companyList"
              :render-after-expand="true"
              :props="treeProps"
              node-key="id"
              check-strictly
              multiple
              collapse-tags
              show-checkbox
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注，最多50个字" :rows="2" :maxlength="50" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { getUser, updateUser, addUser } from "@/api/system/user"
import { getAllCompanies } from '@/api/company/company'
import { listDepartment } from "@/api/company/department"
import { md5 } from '@/utils/md5'
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex")

const userRef = ref()
const emits = defineEmits(['cancel', 'confirm'])

const form = ref({
  userId: undefined,
  coId: null,                 // 所属公司id
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: undefined,
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: "0",
  remark: undefined,
  roleIds: [],
  dataPermissions: 2,         // 数据权限:1全部,2自定义
  companyId: [],            // 数据权限集合
})
const postOptions = ref([])
const roleOptions = ref([])
const companyList = ref([])
const departList = ref([])
const expandedKeys = ref([])
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.state == 2 || data.check == false
  }
}
const rules = {
  userName: [{ required: true, message: "登录用户名不能为空", trigger: "blur" }, { min: 2, max: 20, message: "登录用户名长度必须介于 2 和 20 之间", trigger: "blur" }],
  nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 6, max: 20, message: "用户密码长度必须介于 6 和 20 之间", trigger: "blur" }, { pattern: /^(((?=.*\d)(?=.*[a-zA-Z]))|((?=.*\d)(?=.*[\W_]))|((?=.*[a-zA-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]))).{6,20}$/, message: "用户密码需包含大小写字母、数字和特殊字符中的至少两种", trigger: "blur" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  phonenumber: [{ required: false, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  dataPermissions: [{ required: true, trigger: "blur" }],
  companyId: [{ required: true, message: '请选择数据权限', trigger: "blur" }],
  coId: [{ required: true, message: '请选择所属公司', trigger: "blur" }],
  deptId: [{ required: true, message: '请选择所属部门', trigger: "blur" }],
  roleIds: [{ required: true, message: '请选择用户角色', trigger: "blur" }],
}

const pageInit = (uid) => {
  getUser(uid || '').then(response => {
    postOptions.value = response.posts
    roleOptions.value = response.roles
    if (uid) {
      form.value = response.data
      form.value.roleIds = response.roleIds
      form.value.password = ""
      const arr = form.value.companyId.split(',')
      form.value.companyId = []
      arr.forEach(val => {
        if (val) {
          form.value.companyId.push(Number(val))
        }
      })
      // if (form.value.coId) {
      //   getDepartList()
      // }
    }
  })
}

const handleCompanyChange = () => {
  form.value.deptId = null
  getDepartList()
}

/** 公司列表 */
const getCompanyList = () => {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

/** 部门列表 */
const getDepartList = () => {
  const params = {
    pageNum: 1,
    pageSize: 200,
    companyId: form.value.coId
  }
  listDepartment(params).then(response => {
    departList.value = response.rows
  })
}

const onCancel = () => {
  userRef.value.resetFields()
  emits('cancel')
}

const onConfirm = () => {
  userRef.value.validate(valid => {
    if (valid) {
      let params = {
        ...form.value,
        password: md5(form.value.password)
      }
      if (form.value.dataPermissions == 1) {
        params.companyId = ''
      } else {
        params.companyId = form.value.companyId.join(',')
      }
      if (form.value.userId) {
        delete params.password
        updateUser(params).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          userRef.value.resetFields()
          emits('confirm')
        })
      } else {
        addUser(params).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          userRef.value.resetFields()
          emits('confirm')
        })
      }
    }
  })
}

getCompanyList()

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>